package com.horay.springbootdemo.data.source.multiple;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * 服务启动类
 *
 * @author heyingcheng
 * @date 2019/10/31 21:29
 */
@Slf4j
@EnableTransactionManagement
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, JdbcTemplateAutoConfiguration.class})
public class DataSourceMultipleApplcation implements CommandLineRunner {

    @Autowired
    private DataSource fooDataSource;
    @Autowired
    private DataSource barDataSource;
    @Autowired
    private JdbcTemplate fooJdbcTemplate;
    @Autowired
    private JdbcTemplate barJdbcTemplate;

    public static void main(String[] args) {
        SpringApplication.run(DataSourceMultipleApplcation.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        showConnection();
        showData();
    }

    private void showConnection() throws SQLException {
        log.info("fooDataSource:[{}]", fooDataSource.toString());
        Connection fooConnection = fooDataSource.getConnection();
        log.info("fooConnection:[{}]", fooConnection.toString());

        log.info("barDataSource:[{}]", barDataSource.toString());
        Connection barConnection = barDataSource.getConnection();
        log.info("barConnection:[{}]", barConnection.toString());
    }

    private void showData() {
        fooJdbcTemplate.queryForList("SELECT * FROM foo").forEach(row -> log.info(row.toString()));
        barJdbcTemplate.queryForList("SELECT * FROM bar").forEach(row -> log.info(row.toString()));
    }

}
